package org.mj.hz.converter.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.ClassUtils;


import java.nio.charset.Charset;

/**
 * FAST_JSON
 */
public class MjFastjsonConverter implements MjJsonConverter  {

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    @Override
    public <T> byte[] serialize(T t) {
        if (null == t) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> targetType) {
        if (null == bytes || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        //禁用关键字检测
        if (ClassUtils.isPrimitiveOrWrapper(targetType) || targetType.equals(String.class)) {
            str = "'"+str+"'";
        }
        return JSON.parseObject(str, targetType, Feature.DisableSpecialKeyDetect);
    }


}